package com.webserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {
	
	private InputStream in;
	private PrintStream out;
	
//	private static final String WEB_PATH = "html";
	
	public Processor(Socket socket){
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
			sendErrorMessage(400, "the HTTP is invalid!");
		}
	}
	
	public String parseFileName(){
		String fileName = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		try {
			String httpHeader = br.readLine();
			System.out.println("httpHeader: " + httpHeader);
			fileName = httpHeader.split(" ")[1];
		} catch (Exception e) {
			e.printStackTrace();
			sendErrorMessage(400, "the HTTP is invalid!");
		}
		return fileName;
	}
	
	public void sendResultContent(String fileName){
		if(fileName == null || "".equals(fileName) || "/".equals(fileName)){
			sendErrorMessage(400, "page not found!");
		}
		File file = new File(System.getProperty("user.dir") + File.separator + "webApps" + File.separator + fileName);
		if(!file.exists()){
			System.out.println("File not found!");
			sendErrorMessage(404, "page not found!");
			return;
		}
		byte[] data = new byte[(int)file.length()];
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			fis.read(data);
			out.println("HTTP/1.0 200 ResultContent"); 
			out.println("content-length:"+data.length);
			out.println();
			out.write(data);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
			sendErrorMessage(500, "Server error!");
		} finally{
				out.close();
				try {
					fis.close();
				} catch (IOException e1) {
					e1.printStackTrace();
					sendErrorMessage(500, "Server error!");
				}
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
				sendErrorMessage(500, "Server error!");
			}
		}
	}
	
	public void sendErrorMessage(int errorCode, String errorMsg){
		out.println("HTTP/1.0 " + errorCode + " " + errorMsg); 
		out.println("content-type:text/html");
		out.println();
		out.println("<html>");
		out.println("<head>");
		out.println("<title>Error Message</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>Error: " + errorCode + " " + errorMsg + "</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
			sendErrorMessage(500, "Server error!");
		}
	}
	
	public void run(){
		String fileName = parseFileName();
		sendResultContent(fileName);
	}
}
